/***********************************************************************

	This file is part of KEEL-software, the Data Mining tool for regression, 
	classification, clustering, pattern mining and so on.

	Copyright (C) 2004-2010
	
	F. Herrera (herrera@decsai.ugr.es)
    L. SÃ¡nchez (luciano@uniovi.es)
    J. AlcalÃ¡-Fdez (jalcala@decsai.ugr.es)
    S. GarcÃ­a (sglopez@ujaen.es)
    A. FernÃ¡ndez (alberto.fernandez@ujaen.es)
    J. Luengo (julianlm@decsai.ugr.es)

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see http://www.gnu.org/licenses/
  
**********************************************************************/

package keel.GraphInterKeel.datacf.visualizeData;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import keel.GraphInterKeel.datacf.util.KeelFileFilter;
import keel.GraphInterKeel.util.Path;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * <p>
 * @author Written by Juan Carlos FernÃ¡ndez and Pedro Antonio GutiÃ©rrez(University of CÃ³rdoba) 23/10/2008
 * @version 1.0
 * @since JDK1.5
 * </p>
 */
public class VisualizePanelCharts2D extends javax.swing.JPanel {

    /**
     * <p>
     * Class for visualizing charts in two dimensions
     * </p>
     */

    /**
     * <p>
     * Constructor that initializes the panel
     * </p>
     */
    public VisualizePanelCharts2D() {
        initComponents();
    }

    /**
     * <p>
     * This method is called from within the constructor to
     * initialize the form.
     * </p>
     * <p>
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     * </p>
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        chartjScrollPane = new javax.swing.JScrollPane();
        imagejLabel = new javax.swing.JLabel();
        selectAttributesjPanel = new javax.swing.JPanel();
        attribute1jLabel = new javax.swing.JLabel();
        attribute2jLabel = new javax.swing.JLabel();
        attribute1jComboBox = new javax.swing.JComboBox();
        attribute2jComboBox = new javax.swing.JComboBox();
        pngjLabel = new javax.swing.JLabel();
        pdfjLabel = new javax.swing.JLabel();
        topngjButton = new javax.swing.JButton();
        topdfjButton = new javax.swing.JButton();
        ViewChartjPanel = new javax.swing.JPanel();
        ViewChartjButton = new javax.swing.JButton();

        setName("Form"); // NOI18N

        chartjScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Chart"));
        chartjScrollPane.setName("chartjScrollPane"); // NOI18N

        imagejLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imagejLabel.setToolTipText("Click to Expand");
        imagejLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        imagejLabel.setName("imagejLabel"); // NOI18N
        imagejLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                imagejLabelMouseClicked(evt);
            }
        });
        chartjScrollPane.setViewportView(imagejLabel);

        selectAttributesjPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Select Attributes"));
        selectAttributesjPanel.setName("selectAttributesjPanel"); // NOI18N

        attribute1jLabel.setText("Attribute 1");
        attribute1jLabel.setName("attribute1jLabel"); // NOI18N

        attribute2jLabel.setText("Attribute 2");
        attribute2jLabel.setName("attribute2jLabel"); // NOI18N

        attribute1jComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        attribute1jComboBox.setToolTipText("Select attribute 1");
        attribute1jComboBox.setName("attribute1jComboBox"); // NOI18N

        attribute2jComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        attribute2jComboBox.setToolTipText("Select attribute 2");
        attribute2jComboBox.setName("attribute2jComboBox"); // NOI18N

        pngjLabel.setText("Convert to PNG");
        pngjLabel.setName("pngjLabel"); // NOI18N

        pdfjLabel.setText("Convert to PDF");
        pdfjLabel.setName("pdfjLabel"); // NOI18N

        topngjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/keel/GraphInterKeel/resources/ico/datacf/toPNG.png"))); // NOI18N
        topngjButton.setToolTipText("Export Chart to PNG image");
        topngjButton.setName("topngjButton"); // NOI18N
        topngjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                topngjButtonActionPerformed(evt);
            }
        });

        topdfjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/keel/GraphInterKeel/resources/ico/datacf/toPDF.png"))); // NOI18N
        topdfjButton.setToolTipText("Export Chart to PDF image");
        topdfjButton.setName("topdfjButton"); // NOI18N
        topdfjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                topdfjButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout selectAttributesjPanelLayout = new javax.swing.GroupLayout(selectAttributesjPanel);
        selectAttributesjPanel.setLayout(selectAttributesjPanelLayout);
        selectAttributesjPanelLayout.setHorizontalGroup(
            selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, selectAttributesjPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(attribute1jLabel)
                    .addComponent(attribute2jLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(attribute1jComboBox, 0, 399, Short.MAX_VALUE)
                    .addComponent(attribute2jComboBox, 0, 399, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(selectAttributesjPanelLayout.createSequentialGroup()
                        .addComponent(topngjButton)
                        .addGap(21, 21, 21))
                    .addGroup(selectAttributesjPanelLayout.createSequentialGroup()
                        .addComponent(pngjLabel)
                        .addGap(18, 18, 18)))
                .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(selectAttributesjPanelLayout.createSequentialGroup()
                        .addComponent(topdfjButton)
                        .addGap(19, 19, 19))
                    .addGroup(selectAttributesjPanelLayout.createSequentialGroup()
                        .addComponent(pdfjLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        selectAttributesjPanelLayout.setVerticalGroup(
            selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(selectAttributesjPanelLayout.createSequentialGroup()
                .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(selectAttributesjPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(attribute1jLabel)
                            .addComponent(attribute1jComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(14, 14, 14)
                        .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(attribute2jLabel)
                            .addComponent(attribute2jComboBox)))
                    .addGroup(selectAttributesjPanelLayout.createSequentialGroup()
                        .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(pdfjLabel)
                            .addComponent(pngjLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(selectAttributesjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(topngjButton)
                            .addComponent(topdfjButton))))
                .addContainerGap())
        );

        ViewChartjPanel.setName("ViewChartjPanel"); // NOI18N
        ViewChartjPanel.setLayout(new java.awt.GridBagLayout());

        ViewChartjButton.setText("View Chart");
        ViewChartjButton.setToolTipText("Generate chart");
        ViewChartjButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        ViewChartjButton.setName("ViewChartjButton"); // NOI18N
        ViewChartjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ViewChartjButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        ViewChartjPanel.add(ViewChartjButton, gridBagConstraints);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(selectAttributesjPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ViewChartjPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE)
            .addComponent(chartjScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(selectAttributesjPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chartjScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ViewChartjPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void ViewChartjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ViewChartjButtonActionPerformed
    // Show comparing chart
    if ((this.attribute1jComboBox.getSelectedIndex() == -1) || (this.attribute2jComboBox.getSelectedIndex() == -1)) {
        JOptionPane.showMessageDialog(this,
                "There are no attributes selected", "Error", 2);
    } else if (((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeTypeIndex(this.attribute1jComboBox.getSelectedIndex()).equals(
            "nominal") && ((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeTypeIndex(this.attribute2jComboBox.getSelectedIndex()).equals(
            "nominal")) {
        // Error message
        JOptionPane.showMessageDialog(this,
                "Only one attribute can be nominal", "Error", 2);
    } else if (((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeTypeIndex(this.attribute1jComboBox.getSelectedIndex()).equals(
            "nominal")) {
        // Nominal in x axis --> vertical
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        boolean legend = false;
        for (int i = 0; i < ((VisualizePanel) (this.getParent()).getParent()).getData().getNData(); i++) {
            String column = ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i, this.attribute1jComboBox.getSelectedIndex());
            String row = "";
            if (((VisualizePanel) (this.getParent()).getParent()).getOutAttribute() != -1 && this.attribute1jComboBox.getSelectedIndex() != ((VisualizePanel) (this.getParent()).getParent()).getOutAttribute()) {
                row = "Class " + ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i, ((VisualizePanel) (this.getParent()).getParent()).getOutAttribute());
                legend = true;
            }
            String valor = ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i, this.attribute2jComboBox.getSelectedIndex());
            if (valor != null && column != null) {
                if (dataset.getColumnIndex(column) == -1 || dataset.getRowIndex(row) == -1) {
                    dataset.addValue(Double.valueOf(valor).doubleValue(),
                            row, column);
                } else {
                    dataset.incrementValue(Double.valueOf(valor).doubleValue(), row, column);
                }
            }
        }

        this.chart2 = ChartFactory.createBarChart3D("", ((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeIndex(this.attribute1jComboBox.getSelectedIndex()),
                ((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeIndex(this.attribute2jComboBox.getSelectedIndex()),
                dataset, PlotOrientation.VERTICAL, legend, false, false);
        this.chart2.setTitle(this.attribute1jComboBox.getSelectedItem().toString() + " vs " + this.attribute2jComboBox.getSelectedItem().toString());
        this.chart2.setBackgroundPaint(new Color(0xFFFFFF));
        BufferedImage image = this.chart2.createBufferedImage(600, 450);
        this.imagejLabel.setIcon(new ImageIcon(image));
        this.topdfjButton.setEnabled(true);
        this.topngjButton.setEnabled(true);
    } else if (((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeTypeIndex(this.attribute2jComboBox.getSelectedIndex()).equals(
            "nominal")) {
        // Nominal in y axis --> horizontal
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        boolean legend = false;
        try {
            for (int i = 0; i < ((VisualizePanel) (this.getParent()).getParent()).getData().getNData(); i++) {
                String column = ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i, this.attribute2jComboBox.getSelectedIndex());
                String row = "";
                if (((VisualizePanel) (this.getParent()).getParent()).getOutAttribute() != -1 && this.attribute2jComboBox.getSelectedIndex() != ((VisualizePanel) (this.getParent()).getParent()).getOutAttribute()) {
                    row = "Class " + ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i, ((VisualizePanel) (this.getParent()).getParent()).getOutAttribute());
                    legend = true;
                }
                String valor = ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i, this.attribute1jComboBox.getSelectedIndex());
                if (valor != null) {
                    if (dataset.getColumnIndex(column) == -1 || dataset.getRowIndex(row) == -1) {
                        dataset.addValue(Double.valueOf(valor).doubleValue(), row, column);
                    } else {
                        dataset.incrementValue(Double.valueOf(valor).doubleValue(), row, column);
                    }
                }
            }
        } catch (ArrayIndexOutOfBoundsException exp) {
            JOptionPane.showMessageDialog(
                    this,
                    "The data set contains some errors. This attribute can not be visualized",
                    "Error", 2);
        }
        this.chart2 = ChartFactory.createBarChart3D("",
                ((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeIndex(this.attribute2jComboBox.getSelectedIndex()),
                ((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeIndex(this.attribute1jComboBox.getSelectedIndex()),
                dataset, PlotOrientation.HORIZONTAL, legend, false, false);
        this.chart2.setTitle(this.attribute1jComboBox.getSelectedItem().toString() + " vs " + this.attribute2jComboBox.getSelectedItem().toString());
        this.chart2.setBackgroundPaint(new Color(0xFFFFFF));
        BufferedImage image = this.chart2.createBufferedImage(579, 330);
        this.imagejLabel.setIcon(new ImageIcon(image));
        this.topdfjButton.setEnabled(true);
        this.topngjButton.setEnabled(true);
    } else {
        XYSeriesCollection juegoDatos = new XYSeriesCollection();
        boolean legend = false;
        if (((VisualizePanel) (this.getParent()).getParent()).getOutAttribute() != -1) {
            legend = true;
            Vector outputRang = ((VisualizePanel) (this.getParent()).getParent()).getData().getRange(((VisualizePanel) (this.getParent()).getParent()).getOutAttribute());
            XYSeries series[] = new XYSeries[outputRang.size()];
            for (int i = 0; i < outputRang.size(); i++) {
                series[i] = new XYSeries("Class " + outputRang.elementAt(i));
                juegoDatos.addSeries(series[i]);
            }
            for (int i = 0; i < ((VisualizePanel) (this.getParent()).getParent()).getData().getNData(); i++) {
                int clase = outputRang.indexOf(((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i,
                        ((VisualizePanel) (this.getParent()).getParent()).getOutAttribute()));
                String valor1 = ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i,
                        this.attribute1jComboBox.getSelectedIndex());
                String valor2 = ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i,
                        this.attribute2jComboBox.getSelectedIndex());
                if (valor1 != null) {
                    series[clase].add(Double.valueOf(valor1).doubleValue(),
                            Double.valueOf(valor2).doubleValue());
                }
            }
        } else {
            XYSeries series = new XYSeries("RegresiÃÂ³n");
            juegoDatos.addSeries(series);
            for (int i = 0; i < ((VisualizePanel) (this.getParent()).getParent()).getData().getNData(); i++) {
                String valor1 = ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i,
                        this.attribute1jComboBox.getSelectedIndex());
                String valor2 = ((VisualizePanel) (this.getParent()).getParent()).getData().getDataIndex(i,
                        this.attribute2jComboBox.getSelectedIndex());
                if (valor1 != null) {
                    series.add(Double.valueOf(valor1).doubleValue(), Double.valueOf(valor2).doubleValue());
                }
            }

        }
        // Numeric values
        this.chart2 = ChartFactory.createScatterPlot("",
                ((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeIndex(this.attribute1jComboBox.getSelectedIndex()),
                ((VisualizePanel) (this.getParent()).getParent()).getData().getAttributeIndex(this.attribute2jComboBox.getSelectedIndex()), juegoDatos,
                PlotOrientation.VERTICAL, legend, false, false);
        this.chart2.setTitle(this.attribute1jComboBox.getSelectedItem().toString() + " vs " + this.attribute2jComboBox.getSelectedItem().toString());
        this.chart2.setBackgroundPaint(new Color(0xFFFFFF));
        BufferedImage image = this.chart2.createBufferedImage(579, 330);
        this.imagejLabel.setIcon(new ImageIcon(image));
        this.topdfjButton.setEnabled(true);
        this.topngjButton.setEnabled(true);
    }
}//GEN-LAST:event_ViewChartjButtonActionPerformed

private void imagejLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imagejLabelMouseClicked
    if (this.chart2 != null) {
        ChartFrame frame = new ChartFrame("Attribute comparison", chart2,
                true);
        frame.pack();
        frame.setBackground(new Color(225, 225, 225));
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }
        frame.setLocation((screenSize.width - frameSize.width) / 2,
                (screenSize.height - frameSize.height) / 2);
        frame.setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/keel/GraphInterKeel/resources/ico/logo/logo.gif")));
        frame.setVisible(true);
    }
}//GEN-LAST:event_imagejLabelMouseClicked

private void topngjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topngjButtonActionPerformed
    // Save chart as a PNG image
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("png");
    fileFilter.setFilterName("PNG images (.png)");
    chooser.setFileFilter(fileFilter);
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());

    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".png")) {
            // Add correct extension
            nombre += ".png";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this, "File " + nombre + " already exists. Do you want to replace it?",
                "Confirm", JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                chart2.setBackgroundPaint(Color.white);
                ChartUtilities.saveChartAsPNG(new File(nombre), chart2,
                        1024, 768);
            } catch (Exception exc) {
            }
        }
    }
}//GEN-LAST:event_topngjButtonActionPerformed

private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this, "File " + nombre + " already exists. Do you want to replace it?",
                "Confirm", JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412,
                        new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}//GEN-LAST:event_topdfjButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ViewChartjButton;
    private javax.swing.JPanel ViewChartjPanel;
    private javax.swing.JComboBox attribute1jComboBox;
    private javax.swing.JLabel attribute1jLabel;
    private javax.swing.JComboBox attribute2jComboBox;
    private javax.swing.JLabel attribute2jLabel;
    private javax.swing.JScrollPane chartjScrollPane;
    private javax.swing.JLabel imagejLabel;
    private javax.swing.JLabel pdfjLabel;
    private javax.swing.JLabel pngjLabel;
    private javax.swing.JPanel selectAttributesjPanel;
    private javax.swing.JButton topdfjButton;
    private javax.swing.JButton topngjButton;
    // End of variables declaration//GEN-END:variables

    /** JFreeChart */
    protected JFreeChart chart2;

    /**
     * <p>
     * Sets a JFreeChart chart
     * </p>
     * @param chart JFreechart for image
     */
    public void setChart(JFreeChart chart) {
        this.chart2 = chart;
    }

    /**
     * <p>
     * Gets a JFreeChart from the image
     * </p>
     * @return JFreeChart from the image
     */
    public JFreeChart getChart() {
        return this.chart2;
    }

    /**
     * <p>
     * Detetes all attributes from the first combo box
     * </p>
     */
    public void deteleteAttributes1() {
        this.attribute1jComboBox.removeAllItems();
    }

    /**
     * <p>
     * Adds attributes to the first combo box
     * </p>
     * @param attribute1 Attribute to add
     */
    public void addAtribute1(String attribute1) {
        this.attribute1jComboBox.addItem(attribute1);
    }

    /**
     * <p>
     * Deletes all attributes from the second combo box
     * </p>
     */
    public void deteleteAttributes2() {
        this.attribute2jComboBox.removeAllItems();
    }

    /**
     * <p>
     * Adds attributes to the second combo box
     * </p>
     * @param attribute2 Attribute to add
     */
    public void addAtribute2(String attribute2) {
        this.attribute2jComboBox.addItem(attribute2);
    }

    /**
     * <p>
     * Sets the image for attributes
     * </p>
     * @param image Image for attributes
     */
    public void setImage(BufferedImage image) {
        if (image == null) {
            this.imagejLabel.setIcon(null);
        } else {
            this.imagejLabel.setIcon(new ImageIcon(image));
        }
    }

    /**
     * <p>
     * Enables png format
     * </p>
     * @param value State of enabling png format
     */
    public void enablePNG(boolean value) {
        this.topngjButton.setEnabled(value);
    }

    /**
     * <p>
     * Enables pdf format
     * </p>
     * @param value State of enabling pdf format
     */
    public void enablePDF(boolean value) {
        this.topdfjButton.setEnabled(value);
    }
}
